package org.citywithincity.jobqueue;

import java.util.concurrent.BlockingQueue;

class PcQueueThread extends ServiceThread implements
		JobQueue {

	private BlockingQueue<Object> mQueue;
	private JobHandlerManager hander;
	private QueueListener listener;

	public PcQueueThread(BlockingQueue<Object> queue,QueueListener listener) {
		mQueue = queue;
		this.listener = listener;
	}
	
	public void setHandler(JobHandlerManager hander) {
		this.hander = hander;
	}

	public synchronized void stop() {
		if (!isRunning)
			return;
		isRunning = false;
		thread.interrupt();
	}

	protected boolean repetitionRun() {
		Object job;
		try {
			// Take a request from the queue.
			job = mQueue.take();
		} catch (InterruptedException e) {
			// We may have been interrupted because it was time to quit.
			if (!isRunning) {
				return false;
			}
			return true;
		}
		//如果任务被取消了
		hander.onExecuteJob(job);
		listener.onRemoveJob(job);
		return true;
	}

	@Override
	public void add(Object job) {
		mQueue.add(job);
	}
}
